<?php

namespace App\Http\Service;
use Illuminate\Support\Facades\DB;
use App\Libs\TokenLibrary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Libs\HouseIndicator;
use App\Utils\RedisUtil;
use Illuminate\Support\Facades\Config;

class BaseService
{
    public  $userId=0;
    private $houseindicator; 
    public  $userData=[];
    public  $admin_user=[];
    private $visit_arr=[
            'HouseController/detail',
           // 'UserVisitController/add',
    ];
    private $no_need_permission = [
            'LoginController/register',
            'LoginController/login',



    ];
    public  $cpage;
    public  $climit;
    public function __construct()
    {
        $this->cpage=config('page.page');
        ///dd($this->cpage);exit;
        $this->climit=config('page.limit');
       /* $this->domain_name();
        $controller_method=$this->path();
        $res=$this->getTokenUserinfo();
        if(!in_array($controller_method,$this->no_need_permission)){
            //需要校验的
            if(!$res){
                $msg=[
                    'code'=>201,
                    'message'=>'请登录'
                ];
                $result = [
                    'data'=> $msg
                ];
                echo json_encode ($msg);
                exit;
            }

        }*/
       // die("sdf");
        //dd($this->userId);
        //插入浏览记录
        /*if(in_array($controller_method,$this->visit_arr)&&$this->userId>0){
            $house_code=Request()->input("house_code");
            $userId=$this->userId;
            $city_code=Request()->input("city_code");
            $this->insert_userVisitadd($userId,$house_code,$city_code);
        }*/

     


    }
    public function domain_name()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        // 允许请求的类型
        header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE');
        // 设置是否允许发送 cookies
        header('Access-Control-Allow-Credentials: true');
        // 设置允许自定义请求头的字段
        header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods,Authorization,token,Accesstoken,Refreshtoken');
        //允许axios获取响应头中的Authorization
       // header('Access-Control-Expose-Headers', 'Authorization');
        //运行客户端携带证书式访问
        //header('Access-Control-Allow-Credentials', 'true');

    }
    //根据路由添加历史记录
    public function insert_userVisitadd($userId,$house_code,$city_code)
    {
        $res=DB::connection('mysql_erp')->table("house")->where(['code'=>$house_code])->select("city_code")->get()->toArray();
        $res=(array)$res[0];
        //dd($res[0]);
        if(empty($city_code)){
            $city_code=$res['city_code'];
        }
        $first=DB::connection('mysql_erp')->table("user_visit")->where(['house_code'=>$house_code,'user_id'=>$userId])->first();
        if(!$first){
            $create_time=$update_time=time();
            $status='1';
            DB::connection('mysql_erp')->insert('INSERT INTO `sls_user_visit` (`city_code`, `house_code`,`user_id`,`status`,`create_time`,`update_time`) VALUES (?, ?,?, ?, ?, ?)', [$city_code,$house_code,$userId,$status,$create_time,$update_time]);

        }
        
    }
    //根据token 获取id
    protected function getTokenUserinfo()
    {
        $access_token= isset($_SERVER['HTTP_ACCESSTOKEN'])?$_SERVER['HTTP_ACCESSTOKEN']:'';
        $refresh_token= isset($_SERVER['HTTP_REFRESHTOKEN'])?$_SERVER['HTTP_REFRESHTOKEN']:'';
        if(empty($access_token)){
            return false;
        }else{
            $token=$access_token;
        }
        $authToken = trim(ltrim($token,'bearer'));

        $res = TokenLibrary::validateToken($token);
        //dd($res);
        if($res==false){
            return false;
        }else{
            $this->userId=$res->data->user_id;
            $userinfo=(array)$this->userData=$res->data;
            $data = (array)$res;
            $token_cache = cache()->get("token_http_".$userinfo['user_id']);
           // dd($token_cache);
            if($token_cache != $authToken){
                $this->userId=0;
                return false;
            }

            //redis 验证
            $userid=$this->userId;
            $key="client_api:".$userid;
            $data = RedisUtil::getData($key);
           // dd($data);
            if(empty($data)){
                return false;
            }
            //获取user表中的信息
            $userinfo=DB::connection('mysql_erp')->select("SELECT * FROM `sls_user` where id='$userid'");
            //dd($userinfo);
            if(empty($userinfo)){
                $msg=[
                    'code'=>'401',
                    'message' =>'请最终登录9',
                ];
                echo json_encode($msg);
                exit;
            }
            $userinfo=(array)$userinfo['0'];
            $request=Request();
            $userinfo['iat']=$res->iat;
            $request->user_info=$userinfo;
            //$request->user_info['iat']='3';
            //dd($res);exit;
            return true;
        }

    }

    private function path()
    {
        $route = Route::current();
        $controllerName = class_basename($route->getAction()['controller']);
        list($controller, $method) = explode('@', $controllerName);
        $controller_method=$controller.'/'.$method;
        return $controller_method;
    }

    //组织：城市管理员、品牌加盟商、店长、组长、组员
    //角色标识：supermange 超管、chinamanage 全国管理员、manage 管理员、service 客服、finance 财务

    /**
     * 操作成功返回
     */
    protected function success($data = [], $msg = '操作成功', $code = 200)
    {
        if(empty($data)){
            $data=[];
        }
        $alert=[
            'code' => $code,
            'message' => $msg,
            'data' => $data
        ];
        echo json_encode($alert);
        exit;
    }
    protected function success1($data = [], $msg = '操作成功', $code = 200)
    {
        $alert='success';
        echo json_encode($alert);
        exit;
    }

    /**
     * 操作失败返回
     */
    protected function error($msg = '操作失败', $code = 0, $data = [])
    {
        if(empty($data)){
            $data=[];
        }
        $alert=[
            'code' => $code,
            'message' => $msg,
            'data' => $data
        ];
        echo json_encode($alert);
        exit;
    }
    protected function error1($msg = '操作失败', $code = 0, $data = [])
    {
        $alert='failure';
        echo json_encode($alert);
        exit;
    }

    /**
     * 处理空字符串
     */
    protected function dealEmptyData($data)
    {
        if (!empty($data) && is_array($data)) {
            foreach ($data as $k => $v) {
                if (empty($v) && $v !== 0) {
                    $data[$k] = '';
                }
            }
        }
        return $data;
    }
  
   
    //根据经纬度算两点之间的距离
    protected function calculateDistance($latitude1, $longitude1, $latitude2, $longitude2,$gongli=1) {
        if(empty($latitude1)||empty($longitude1)||empty($latitude2)||empty($longitude2)){
            return  false;
        }
        // 将纬度和经度转换为弧度
        $latitude1 = deg2rad($latitude1);
        $longitude1 = deg2rad($longitude1);
        $latitude2 = deg2rad($latitude2);
        $longitude2 = deg2rad($longitude2);
     
        // 计算纬度和经度的差值
        $deltaLatitude = $latitude2 - $latitude1;
        $deltaLongitude = $longitude2 - $longitude1;
     
        // 计算Haversine公式中的a
        $a = sin($deltaLatitude / 2) * sin($deltaLatitude / 2) +
             cos($latitude1) * cos($latitude2) *
             sin($deltaLongitude / 2) * sin($deltaLongitude / 2);
     
        // 计算Haversine公式中的c
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
     
        // 地球平均半径（单位：公里）
        $earthRadius = 6371;
     
        // 计算距离
        $distance = $earthRadius * $c;
        if($distance<=$gongli){
            return true;
        }

        return false;
     
       
    }



    public function curl_post_https($url,$data){//模拟提交数据函数
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
          curl_setopt($curl, CURLOPT_POST, 1);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }



    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    
    public function uniqueId(){
        return uniqid(); // 使用唯一ID作为任务标识
    }

    //钱转换为万单位
    public function formatToWan($number) {
        // 确保输入是数字
        if (!is_numeric($number)) {
            return $number;
        }
        
        // 将数字除以10000并保留两位小数
        $wan = number_format($number / 10000, 2);
        
        return $wan . "万";
    }
    //打印sql   在需要打印SQL的语句前添加
    // $this->getLastSql();
    public function getLastSql()
    {
        DB::listen(function ($sql) {

            foreach ($sql->bindings as $i => $binding) {
                if ($binding instanceof \DateTime) {
                    $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                } else {
                    if (is_string($binding)) {
                        $sql->bindings[$i] = "'$binding'";
                    }
                }
            }
           // die($sql->bindings);
            $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
            $query = vsprintf($query, $sql->bindings);

            $logFile = fopen(
                    storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . 'sql.dat'),
                    'a+'
                );
            fwrite($logFile, '['.date('Y-m-d H:i:s') . '] ' . $query . ';'.PHP_EOL);
            fclose($logFile);


            die($query);
        });
    }

    /**
    * 获取原来EAC图片
    */
    public function getOriginalEacPic($url)
    {
        if(!$url){
            return '';
        }
        return 'https://eac.doufangsls.com/'.$url;
    }

    // 图片展示
    public function showImg($img)
    {
        if(strpos($img,'http') === false ){
            $img=$this->getOriginalEacPic($img);
        }
        return $img;
    }


}
